package http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.util.HashMap;
import java.util.Map;

public class HttpServerTest {

    public static void main(String[] args) throws InterruptedException {

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        NioEventLoopGroup eventExecutors1 = new NioEventLoopGroup();
        serverBootstrap.group(eventExecutors,eventExecutors1)
        .localAddress(9999)
        .channel(NioServerSocketChannel.class)
        .childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {



                channel.pipeline().addLast(new HttpServerCodec());
                channel.pipeline().addLast(new HttpObjectAggregator(512*1024));
                channel.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest  req) throws Exception {


                        // 获取请求的uri
                        String uri = req.uri();
                        Map<String,String> resMap = new HashMap<>();
                        resMap.put("method",req.method().name());
                        resMap.put("uri",uri);
                        String msg = "<html><head><title>test</title></head><body>你请求uri为：" + uri+"</body></html>";
                        // 创建http响应
                        FullHttpResponse response = new DefaultFullHttpResponse(
                                HttpVersion.HTTP_1_1,
                                HttpResponseStatus.OK,
                                Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
                        // 设置头信息
                        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
                        // 将html write到客户端
                        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

                    }
                });
            }
        })
        ;

        ChannelFuture channelFuture = null;
        try {
            channelFuture = serverBootstrap.bind().sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            eventExecutors.shutdownGracefully().sync();
            eventExecutors1.shutdownGracefully().sync();
        }


    }

}
